/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 06 - 05
 * Time: 22:30
 */
class Money implements Cloneable{
    public double money = 10.0;
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    @Override
    public String toString() {
        return "Money{"+"money="+money+'}';
    }
}
class Person implements Cloneable{
    public int age;
    public Money m;//这里用了组合
    public Person(int age){
        this.age = age;
        this.m = new Money();
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person tmp = (Person) super.clone();
        tmp.m = (Money) this.m.clone();//clone()在Money类中虽然是protected修饰，但这里是同一个包下的不同类，所以可以在Person类中通过对象的引用调用Money类的clone()以克隆Money类对象
        return tmp;                    //克隆this.m所指向的内容，谁调用这个方法谁就是this，p1调用了这个方法所以p1是this，克隆p1.m所指向的内容
    }
    @Override
    public String toString() {
        return "Person{"+"age="+age+",m="+m+'}';
    }
}
class Test2 {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person p1 = new Person(10);
        Person p2 = (Person) p1.clone();
        System.out.println(p1);
        System.out.println(p2);
        p2.m.money = 20.0;
        System.out.println(p2);
    }
}

